package com.chatroom.client.ui;

import java.awt.*;
import javax.swing.*;

public class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;

    public LoginFrame() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            UIManager.put("Label.font", new Font("微软雅黑", Font.PLAIN, 14));
            UIManager.put("Button.font", new Font("微软雅黑", Font.PLAIN, 14));
            UIManager.put("TextField.font", new Font("微软雅黑", Font.PLAIN, 14));
            UIManager.put("TextArea.font", new Font("微软雅黑", Font.PLAIN, 14));
        } catch (Exception e) {
            e.printStackTrace();
        }
        setTitle("登录 - ChatRoom");
        setSize(350, 220);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        initUI();
    }

    private void initUI() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel userLabel = new JLabel("用户名:");
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(userLabel, gbc);
        usernameField = new JTextField(15);
        gbc.gridx = 1;
        gbc.gridy = 0;
        panel.add(usernameField, gbc);

        JLabel passLabel = new JLabel("密码:");
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(passLabel, gbc);
        passwordField = new JPasswordField(15);
        gbc.gridx = 1;
        gbc.gridy = 1;
        panel.add(passwordField, gbc);

        loginButton = new JButton("登录");
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(loginButton, gbc);
        registerButton = new JButton("注册");
        gbc.gridx = 1;
        gbc.gridy = 2;
        panel.add(registerButton, gbc);

        add(panel);

        loginButton.addActionListener(e -> onLogin());
        registerButton.addActionListener(e -> onRegister());
    }

    private void onLogin() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        if (UserManager.getInstance().validateUser(username, password)) {
            JOptionPane.showMessageDialog(this, "登录成功！");
            dispose();
            // 进入主聊天界面，传递用户名作为昵称
            new com.chatroom.client.Client(username);
        } else {
            JOptionPane.showMessageDialog(this, "用户名或密码错误！", "登录失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void onRegister() {
        new RegisterFrame(this).setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new LoginFrame().setVisible(true));
    }
}